/*
 * Copyright (c) 2020, Peter Abeles. All Rights Reserved.
 *
 * This file is part of BoofCV (http://boofcv.org).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package boofcv.alg.feature.detect.edge;

import boofcv.alg.misc.ImageMiscOps;
import boofcv.factory.feature.detect.edge.FactoryEdgeDetectors;
import boofcv.struct.image.GrayF32;
import boofcv.struct.image.GrayU8;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 2)
@Measurement(iterations = 5)
@State(Scope.Benchmark)
@Fork(value = 1)
public class BenchmarkDetectEdge {
	GrayF32 input = new GrayF32(640, 480);
	GrayU8 output = input.createSameShape(GrayU8.class);

	final int iterations = 5;

	@Setup public void setup() {
		createImage();
	}

	public void createImage() {
		var rand = new Random(234234);
		for (int i = 0; i < 1000; i++) {
			int width = 10 + rand.nextInt(50);
			int height = 10 + rand.nextInt(50);

			int x = rand.nextInt(input.width);
			int y = rand.nextInt(input.height);

			int x1 = x + width;
			int y1 = y + height;
			if (x1 > input.width) x1 = input.width;
			if (y1 > input.height) y1 = input.height;

			width = x1 - x;
			height = y1 - y;

			ImageMiscOps.fillRectangle(input, rand.nextInt(100), x, y, width, height);
		}
	}

	@Benchmark public void CannyMark() {
		CannyEdge<GrayF32, GrayF32> alg = FactoryEdgeDetectors.canny(2, false, false, GrayF32.class, GrayF32.class);
		for (int i = 0; i < iterations; i++) {
			alg.process(input, 5, 10, output);
		}
	}

	@Benchmark public void CannyTrace() {
		CannyEdge<GrayF32, GrayF32> alg = FactoryEdgeDetectors.canny(2, true, false, GrayF32.class, GrayF32.class);
		for (int i = 0; i < iterations; i++) {
			alg.process(input, 5, 10, output);
		}
	}

	public static void main( String[] args ) throws RunnerException {
		Options opt = new OptionsBuilder()
				.include(BenchmarkDetectEdge.class.getSimpleName())
				.warmupTime(TimeValue.seconds(1))
				.measurementTime(TimeValue.seconds(1))
				.build();

		new Runner(opt).run();
	}
}
